#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
using ll = long long;
int a, b;
int exgcd(int a, int b, ll& x, ll& y)
{
    if (!b)
    {
        x = 1, y = 0;
        return a;
    }
    int d = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
int main()
{
    cin >> a >> b;
    ll x, y;
    exgcd(a, b, x, y);
    cout << (x % b + b) % b << endl;
    return 0;
}